package com.ag.oa.shiro;

import com.ag.oa.core.dao.IUserDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserDao userDao;

    private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    /**
     * 登录认证回调
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        final String username = token.getUsername()==null? "": token.getUsername();
        final String password = token.getPassword()==null? "": String.valueOf(token.getPassword());

        logger.info("用户名: {} 密码: {}", username, password);

        Object hashedCredentials = null;

        // 用户名密码
        if (username.trim().length()==0 || password.trim().length()==0) {
            return new SimpleAuthenticationInfo("username", "password.1"
                    , ByteSource.Util.bytes(username), getName());  //
        }

        // 临时用户数据
        String userId = hashedCredentials==null? "": hashedCredentials.toString();

        // 设置 session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("userId", userId);
        session.setAttribute("userName", username);

        // 从数据库中获取
//        SysUserPO user = userDao.getLoinUserByName(username);
//        if (user==null) {
//            throw  new UnknownAccountException("账号不存在");
//        }
//        if (user.getStatus()==0) {
//            throw new DisabledAccountException("账户已被禁用, 请联系管理员!");
//        }
        return new SimpleAuthenticationInfo(username, hashedCredentials
                , ByteSource.Util.bytes(username), getName());
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName(ShiroUtil.hashAlgorithmName);
        matcher.setHashIterations(ShiroUtil.hashIterations);
        super.setCredentialsMatcher(credentialsMatcher);
    }

    public static void main(String[] args) {

        Object credentials = "yxm.";  // 相当于密码
        Object salt = ByteSource.Util.bytes("yxm");  // 相当于用户名

        Object result = new SimpleHash(ShiroUtil.hashAlgorithmName, credentials, salt
                , ShiroUtil.hashIterations);
        System.out.println(result);
    }

}
